package com.xiang.sql.service;

import java.util.List;

import jakarta.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.api.Util;
import com.xiang.sql.entity.User;
import com.xiang.sql.entity.Setting;
import com.xiang.sql.mapper.SettingMapper;

/**
 * 系统设置 服务实现类
 * 
 * @author mac-xiang
 */
@Service
public class SettingService extends ServiceImpl<SettingMapper, Setting> {
  @Resource
  SettingMapper mapper;

  private QueryWrapper<Setting> readWrapper(JSONObject p, User per) {
    QueryWrapper<Setting> ret = Util.getQuery(p, Setting.class);
    if (per != null && !per.per("系统设置查询")) {
      // ret.eq("`create`", per.id);
    }
    return ret;
  }

  private List<Setting> getList(JSONObject p, User per) {
    return mapper.selectList(readWrapper(p, per));
  }

  private Page<Setting> getPage(Page<Setting> page, JSONObject p, User per) {
    return mapper.selectPage(page == null ? new Page<Setting>(1, 100) : page, readWrapper(p, per));
  }

  public Setting create(JSONObject p, User per) {
    if (per != null && per.per("系统设置创建")) {
      Setting entity = Util.getEntity(p, Setting.class);
      // entity.createTime = null;
      // entity.create = per.id;
      mapper.insert(entity);
      return entity;
    }
    throw new RuntimeException("没有权限");
  }

  public int update(JSONObject p, User per) {
    if (per != null && per.per("系统设置修改")) {
      Setting entity = Util.getEntity(p, Setting.class);
      QueryWrapper<Setting> qw = Util.getQuery(p, Setting.class);
      if (this.count(qw) > 10) {
        throw new RuntimeException("单次修改数量超过10条");
      }
      // entity.create = null;
      return mapper.update(entity, qw);
    }
    throw new RuntimeException("没有权限");
  }

  public Object read(JSONObject p, User per) {
    Page<Setting> page = Util.getPage(p, Setting.class);
    return page == null ? getList(p, per) : getPage(page, p, per);
  }

  public int delete(JSONObject p, User per) {
    if (per != null && per.per("系统设置删除")) {
      QueryWrapper<Setting> q = Util.getQuery(p, Setting.class);
      if (this.count(q) > 10) {
        throw new RuntimeException("删除数据的数量不能超过10条");
      }
      return mapper.delete(q);
    }
    throw new RuntimeException("没有权限");
  }

  public long count(JSONObject p, User per) {
    return this.count(readWrapper(p, per));
  }

  public String getValueById(String id) {
    Setting s = this.getById(id);
    if (s != null) {
      return s.value;
    }
    return null;
  }

  private Boolean distribution = null;

  public boolean getDistribution() {
    if (distribution == null) {
      try {
        distribution = "1".equals(this.getValueById("distribution"));
      } catch (Exception e) {
      }

    }
    return distribution;
  }
}
